package com.fhz.mvitest.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fhz.mvitest.entity.BannerEntity
import com.fhz.mvitest.entity.ResponseEntity
import com.fhz.mvitest.model.BannerRepostory
import com.fhz.mvitest2.intent.BannerIntent
import com.fhz.mvitest2.ui.BannerUIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
/**
 * 时间:2023/5/19
 * @author Mr.Feng
 * 简述: vm类
 */
class BannerViewModel @Inject constructor(private val repostory: BannerRepostory) : ViewModel(){

    val channel = Channel<BannerIntent>(Channel.UNLIMITED)
    //不让外部调用
    private val _state = MutableStateFlow<BannerUIState>(BannerUIState.Init)
    //使用flow来监听
    val state: StateFlow<BannerUIState>
        get() = _state

    init {
        handleIntent()
    }

    //准备处理所有意图
    private fun handleIntent() {
        //起协程准备处理
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is BannerIntent.GetBannerList -> getBannerList()
                    else -> {}
                }
            }
        }
    }

    private fun getBannerList() {
        viewModelScope.launch {
            val bannerList = repostory.getBannerList()
            if(bannerList.errorCode == 200){
                _state.value = BannerUIState.Success(bannerList)
            }else{
                _state.value = BannerUIState.Fail(bannerList)
            }
        }
    }

}